package RFID;


import com.sun.jna.Native;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


/**
 * @author nicepuppy
 * @date 2023/5/18 9:21
 * @description for read RFID equipment
 */
public class RWUtils {

    public static RWOptionService INSTANCE;//动态库声明

    /**
     * 说明：通过静态代码块实例化动态库，并且判断加载 x32 dll还是x64 dll 库
     * */
    static {

        String bits = System.getProperty("sun.arch.data.model");// 获取jdk位数
        System.out.println("jdk 位数：" + bits);
        String ops = System.getProperty("os.name");   // 获取os名称
        System.out.println("操作系统：" + ops);
        if (ops.startsWith("win") || ops.startsWith("Win"))//windows
        {
            if ("32".equals(bits)) {
                System.out.println("当前程序加载了 YW60X-32.dll");
                System.load(System.getProperty("user.dir") + "\\lib\\YW60X-32.dll");
                INSTANCE = (RWOptionService) Native.loadLibrary("YW60X-32", RWOptionService.class);

            } else {
                System.out.println("当前程序加载了 YW60X-64.dll" + "\\SDK\\RfidLib\\TCP_ALL.lib");
                System.out.println(System.getProperty("user.dir"));
                System.load(System.getProperty("user.dir") + "\\SDK\\RfidLib\\TCP_ALL.dll");
                INSTANCE = (RWOptionService) Native.loadLibrary("YW60X-64", RWOptionService.class);
            }

        } else {//其他操作系统
            System.out.println("当前仅支持Windows系统，暂不支持其他操作系统！");
        }
    }


    /**
     * 写卡方法 from liuxiaobao
     *
     * @param readerID     读卡器id
     * @param requestmode  请求模式
     * @param cardtype     卡类型
     * @param lenSn        卡号长度
     * @param cardNo       卡号
     * @param key          秘钥
     * @param blockData    块数据
     * @param blockAddr    块
     * @param buzzerAndLed 是否开启声音和led灯
     * @return boolean    (true:成功 false：失败  )
     */
    public static boolean write(int readerID, int requestmode, short[] cardtype, byte[] lenSn, byte[] cardNo, byte[] key, byte[] blockData, int blockAddr, boolean buzzerAndLed) {

        INSTANCE.YW_USBHIDInitial();
        int rt = 0;
        rt = INSTANCE.YW_RequestCard(readerID, requestmode, cardtype);
        rt = INSTANCE.YW_AntiCollide(readerID, lenSn, cardNo);
        rt = INSTANCE.YW_CardSelect(readerID, lenSn[0], cardNo);
        rt = INSTANCE.YW_KeyAuthorization(readerID, 96, blockAddr, key);
        System.out.println();
        rt = INSTANCE.YW_WriteaBlock(readerID, blockAddr, 16, blockData);
        if (buzzerAndLed) {
            INSTANCE.YW_Led(readerID, 1, 1, 1, 3, 2);
            INSTANCE.YW_Buzzer(readerID, 1, 1, 2);
        }
        INSTANCE.YW_USBHIDFree();
        if (rt > 0) {
            //写卡完成
            System.out.println("写入成功，写入的数据为：" + byteArrayToInt(blockData, 0, true));

            return true;
        }
        //写卡失败
        return false;
    }

    /**
     * 读卡方法 from liuxiaobao
     *
     * @param readerID     读卡器id
     * @param requestmode  请求模式
     * @param cardtype     卡类型
     * @param lenSn        卡号长度
     * @param cardNo       卡号
     * @param key          秘钥
     * @param blockData    块数据
     * @param blockAddr    块
     * @param buzzerAndLed 是否开启声音和led灯
     * @return map   (cardNo:十进制卡号 data：十进制数据  )
     */
    public static Map reader(int readerID, int requestmode, short[] cardtype, byte[] lenSn, byte[] cardNo, byte[] key, byte[] blockData, int blockAddr, boolean buzzerAndLed) {
        Map<String, Integer> resultMap = new HashMap<>();

        INSTANCE.YW_USBHIDInitial();
        int rt = 0;
        rt = INSTANCE.YW_RequestCard(readerID, requestmode, cardtype);
        rt = INSTANCE.YW_AntiCollide(readerID, lenSn, cardNo);
        resultMap.put("cardNo", byteArrayToInt(cardNo, 0, true));
        rt = INSTANCE.YW_CardSelect(readerID, lenSn[0], cardNo);
        rt = INSTANCE.YW_KeyAuthorization(readerID, 96, blockAddr, key);
        rt = INSTANCE.YW_ReadaBlock(readerID, blockAddr, 16, blockData);
        System.out.println();
        if (rt > 0) {
            resultMap.put("data", byteArrayToInt(blockData, 0, true));
        }
        if (rt > 0 && buzzerAndLed) {
            INSTANCE.YW_Led(readerID, 1, 1, 1, 3, 2);
            INSTANCE.YW_Buzzer(readerID, 2, 2, 1);
        }
        INSTANCE.YW_USBHIDFree();

        return resultMap;
    }

    public static void main(String args[]) {
        int readerID = 1001;//读卡器id随意整型
        int requestmode = 38;
        short cardtype[] = new short[1];
        byte lenSn[] = new byte[1];
        byte cardNo[] = new byte[8];
        byte Key[] = new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
        byte blockData[] = new byte[16];
        int blockAddr = 5;

        int eNo = 88188;

        Calendar instance = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        System.out.println(dateFormat.format(instance.getTime()));

/*
          System.out.println(getTimeAdd());*/

/*
        byte[] bytes = intToByteArray(eNo, true);



        for (int i=0;i<bytes.length;i++) {

            blockData[i]=bytes[i];
        }



         boolean flag = write(readerID, requestmode, cardtype, lenSn, cardNo, Key, blockData, blockAddr, true);
       if(true){

           int i = byteArrayToInt(blockData, 0, true);
           System.out.println("eNoInt:"+i);
           System.out.println("写入成功，写入的数据为："+i);
       }*/


        while (true) {
            Map reader = reader(readerID, requestmode, cardtype, lenSn, cardNo, Key, blockData, blockAddr, true);
            System.out.println("cardNo:" + reader.get("cardNo"));
            System.out.println("data:" + reader.get("data"));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
    public static int getTimeAdd(){
        LocalTime now = LocalTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HHmm");
        String timeStr = now.format(dtf);
        if(!timeStr.isEmpty()){
            String times[]= timeStr.split(":");
            return  Integer.parseInt(times[0])+Integer.parseInt(times[1]);
        }
        return -1;
    }


    /**
     * 整型转byte数组 from liuxiaobao
     *
     * @param i     整数
     * @param isBig true:大端模式  false:小端模式
     * @return 数组
     */
    public static byte[] intToByteArray(int i, boolean isBig) {
        byte[] result = new byte[4];
        // 由高位到低位
        if (isBig) {
            result[0] = (byte) ((i >> 24) & 0xFF);
            result[1] = (byte) ((i >> 16) & 0xFF);
            result[2] = (byte) ((i >> 8) & 0xFF);
            result[3] = (byte) (i & 0xFF);
        } else {
            result[3] = (byte) ((i >> 24) & 0xFF);
            result[2] = (byte) ((i >> 16) & 0xFF);
            result[1] = (byte) ((i >> 8) & 0xFF);
            result[0] = (byte) (i & 0xFF);
        }
        return result;
    }

    /**
     * byte数组转整型 from liuxiaobao
     *
     * @param bytes byte数组
     * @param start 起始位
     * @param isBig true:大端模式  false:小端模式
     * @return 整数
     */
    public static int byteArrayToInt(byte[] bytes, int start, boolean isBig) {
        int value = 0;
        if (isBig) {
            value += (bytes[start] & 0x000000FF) << 24;
            value += (bytes[start + 1] & 0x000000FF) << 16;
            value += (bytes[start + 2] & 0x000000FF) << 8;
            value += (bytes[start + 3] & 0x000000FF);
        } else {
            value += (bytes[start] & 0x000000FF);
            value += (bytes[start + 1] & 0x000000FF) << 8;
            value += (bytes[start + 2] & 0x000000FF) << 16;
            value += (bytes[start + 3] & 0x000000FF) << 24;
        }
        return value;
    }


}